// import 'dart:nativewrappers/_internal/vm/lib/ffi_allocation_patch.dart';

import 'package:flutter/material.dart';
import 'package:flutter/animation.dart';
import 'package:dio/dio.dart';
import 'package:get/route_manager.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';




class RegisterScreen extends StatefulWidget {
  @override
  _RegisterScreenState createState() => _RegisterScreenState();
  final dio = Dio(BaseOptions(
  baseUrl: const String.fromEnvironment('BASE_URL', defaultValue: "http://localhost:8080"),
));
}

class _RegisterScreenState extends State<RegisterScreen> with TickerProviderStateMixin {
  late AnimationController _headerController;
  late Animation<Offset> _headerSlide;
  late Animation<double> _headerFade;
  final _formKey = GlobalKey<FormState>();
  String _email = '';
  String _password = '';
  TextEditingController _passwordController = TextEditingController();
  TextEditingController _emailController = TextEditingController();
  bool _obscurePassword = true;

  @override
  void initState() {
    super.initState();
    
    _headerController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 800),
    )..forward();

    _headerSlide = Tween<Offset>(
      begin: Offset(0, -0.2),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _headerController,
      curve: Curves.easeOutQuad,
    ));

    _headerFade = Tween(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _headerController,
        curve: Interval(0.3, 1.0),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Colors.green[50]!,
              Colors.green[100]!,
            ],
          ),
        ),
        child: SafeArea(
          child: SingleChildScrollView(
            padding: EdgeInsets.all(24),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  _buildHeader(),
                  SizedBox(height: 36),
                  _buildEmailField(),
                  SizedBox(height: 24),
                  _buildPasswordField(),
                  SizedBox(height: 24),
                  _buildConfirmPassword(),
                  SizedBox(height: 40),
                  _buildRegisterButton(),
                  SizedBox(height: 28),
                  _buildSocialAuth(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return SlideTransition(
      position: _headerSlide,
      child: FadeTransition(
        opacity: _headerFade,
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text('14:24', style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 14,
                )),
              ],
            ),
            SizedBox(height: 20),
            Text('Financials', style: TextStyle(
              fontSize: 32,
              fontWeight: FontWeight.bold,
              color: Colors.green[800],
              letterSpacing: 1.2,
            )),
            SizedBox(height: 8),
            Text('开启智能财务管理', style: TextStyle(
              color: Colors.grey[700],
              fontSize: 16,
            )),
          ],
        ),
      ),
    );
  }

  Widget _buildEmailField() {
    return TextFormField(
      // onSaved: (val)=> _email = val!,
      controller: _emailController,
      keyboardType: TextInputType.emailAddress,
      decoration: _inputDecoration(Icons.email_outlined, '电子邮箱'),
      validator: (value) => value!.contains('@') ? null : '请输入有效邮箱',
    );
  }

  Widget _buildPasswordField() {
    return TextFormField(
      controller: _passwordController,
      obscureText: _obscurePassword,
      decoration: _inputDecoration(Icons.lock_outlined, '密码').copyWith(
        suffixIcon: IconButton(
          icon: Icon(_obscurePassword 
              ? Icons.visibility_off 
              : Icons.visibility),
          onPressed: () => setState(() => _obscurePassword = !_obscurePassword),
        ),
      ),
      validator: (value) => value!.length >= 6 ? null : '密码至少6位',
    );
  }

  Widget _buildConfirmPassword() {
    return TextFormField(
      obscureText: _obscurePassword,
      decoration: _inputDecoration(Icons.lock_reset, '确认密码'),
      validator: (value){
        print(value);
        print(_password);
       return value==_passwordController.text? null : '密码不一致';
      } 
    );
  }

  InputDecoration _inputDecoration(IconData icon, String label) {
    return InputDecoration(
      labelText: label,
      prefixIcon: Icon(icon, color: Colors.grey[600]),
      floatingLabelStyle: TextStyle(color: Colors.green[700]),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(12),
        borderSide: BorderSide(color: Colors.green, width: 1.5),
      ),
    );
  }

  Widget _buildRegisterButton() {
    return ElevatedButton(
      onPressed: _submitForm,
      style: ElevatedButton.styleFrom(
        foregroundColor: Colors.white, 
        backgroundColor: Colors.green[700],
        padding: EdgeInsets.symmetric(vertical: 18),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        elevation: 4,
        shadowColor: Colors.green.withOpacity(0.3),
      ),
      child: Text('立即注册', style: TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.w600,
        letterSpacing: 1.1,
      )),
    );
  }

  Widget _buildSocialAuth() {
    return Column(
      children: [
        Text('其他方式注册', style: TextStyle(
          color: Colors.grey[600],
        )),
        SizedBox(height: 16),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _buildSocialIcon(Icons.apple),
            SizedBox(width: 24),
            _buildSocialIcon(Icons.facebook),
            SizedBox(width: 24),
            _buildSocialIcon(Icons.gpp_good),
          ],
        ),
      ],
    );
  }

  Widget _buildSocialIcon(IconData icon) {
    return IconButton(
      icon: Icon(icon, size: 32),
      color: Colors.green[700],
      onPressed: () {},
    );
  }

 

  void _submitForm () async{
   
    if (_formKey.currentState!.validate()) {
      
      String email = _emailController.text;
      String password = _passwordController.text;
      var data={
        'email': email,
        'password': password,
      };
      var rsp=await widget.dio.post("/register",data: data);
      print(rsp.data['code']);
      if(rsp.data['code']==200){
    Get.toNamed("/login");
     TDToast.showText('注册成功', context: context);

      }else{

     TDToast.showText('注册失败:${rsp.data['msg']}', context: context);
      }
      
      // 注册逻辑
    }
  }

  @override
  void dispose() {
    _headerController.dispose();
    super.dispose();
  }
}